$(function(){
	var changeNumber = 8;
	var total = 0;
    
	Z.innerTip($('dt form input.text'), 'Search');
    
	var displayProjects = [];
    
	Z.ajax({
		url : Z.url('/project/records'),
		data : {
			category : CATEGORY
		},
		success : function(data){
			total = data.total;
			var html = [];
			$(data.records).each(function(i ,item){
				var summary = item.summary.replace(/\n/g,'<br/>');
				html.push('<dd'+((i + 1)%4?'':' class="change-line"')+'>');
				html.push('<a href="'+Z.url('/project/show/'+item.id)+'">');
				html.push('<img src="'+Z.url('/assets/upload/img/'+item.cover_name)+'" alt="'+item.name+'"/>');
				html.push('<span class="desc">'+item.name+'<span>'+summary+'</span></span>');
				html.push('<span class="loading"><img src="'+Z.url('/assets/img/project-image-loading.gif')+'" alt="loading..."/></span>');
				html.push('</a></dd>');
				displayProjects.push(item.id);
			});
			$('dl#projects').append(html.join(''));
			$('dl#projects a img').load(function(){
				$(this).siblings('span.loading').hide();
			});
		}
	});
    
	window.setInterval(function(){
		if(total < 16){
			return;
		}
		var randIds = getRand(range(displayProjects.length),changeNumber);
		Z.ajax({
			url : Z.url('/project/rand'),
			data: {
				ids : displayProjects,
				category: CATEGORY
			},
			success : function(data){
				$(randIds).each(function(index,item){
					change(item,data[index]);
				});
			}
		});
	}, 8000);
    
	function change(index,data){
		var oldId = $('dl#projects dd').eq(index).find('a').attr('href').replace(/.*\/(\d+)$/,'$1');
		displayProjects = displayProjects.remove(oldId);
		displayProjects.push(data.id);
		$('dl#projects dd').eq(index).find('a').animate({
			'opacity' : 0.1
		},800,function(){
			$('dl#projects dd').eq(index).find('span.loading').show();
			$('dl#projects dd').eq(index).find('a').attr('href',Z.url('/project/show/'+data.id));
			$('dl#projects dd').eq(index).find('a>img').attr('src',Z.url('/assets/upload/img/'+data.cover_name));
			$('dl#projects dd').eq(index).find('a>img').attr('alt',data.name);
			$('dl#projects dd').eq(index).find('a span').html(data.name);
			$('dl#projects dd').eq(index).find('a>img').load(function(){
				$(this).siblings('span.loading').hide();
			});
			$(this).animate({
				'opacity':1
			},300);
		});
	}
    
	function getRand(numbers,count){
		var result = [];
		for(var i=0;i < count;i++){
			var index = Math.ceil(Math.random() * (numbers.length-1));
			result.push(numbers[index]);
			numbers = numbers.del(index);
		}
		return result;
	}

	function range(max,min,step){
		var result = [];
		for(var i = (min||0);i < max; i += (step||1)){
			result.push(i);
		}
		return result;
	}
});